#include "MySocket.h"
#include "PrintInfo.h"
#include <stdexcept>
#include <cstring>


using namespace std;

MyServSocket MS(IP,PORT,AF_INET);

// 构造函数实现
MyServSocket::MyServSocket(const string& host_addr, int port, int sin_family) 
    : port(port) 
{
    // 初始化服务器地址结构
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = sin_family;
    serv_addr.sin_port = htons(port);
    inet_pton(sin_family, host_addr.c_str(), &serv_addr.sin_addr);

    // 初始化socket
    InitSocketfd();
}

void MyServSocket::InitSocketfd() {
    // 创建socket
    if ((socket_fd =socket(serv_addr.sin_family, SOCK_STREAM, 0)) < 0) {
        throw runtime_error("Socket creation error");
    }

    // 绑定地址
    if (bind(socket_fd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        close(socket_fd);
        throw runtime_error("Bind failed");
    }

    // 开始监听
    if (listen(socket_fd, SOMAXCONN) < 0) {
        close(socket_fd);
        throw runtime_error("Listen failed");
    }
}

bool MyServSocket::AcceptConnection(sockaddr_in&client_addr,socketfd&client_fd) {
    socklen_t addr_len = sizeof(client_addr);
    
    client_fd = accept(socket_fd, (sockaddr*)&client_addr, &addr_len);
    if (client_fd < 0) {
        PRINT_ERRNO_AND_STRERROR(errno, "Accept error");
        return false;
    }

    // 记录客户端信息
    clients_fd.insert(client_fd);

    // 输出连接信息
    char client_ip[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, INET_ADDRSTRLEN);
    PRINTF_LOG_AND_DEBUG(LOG_NOTICE, "New connection from: %s:%d", client_ip, ntohs(client_addr.sin_port));
    return true;
}

bool MyServSocket::SendToClient(const socketfd& client_fd,const string& write_buf) {
    ssize_t bytes_sent = 0;
    const char* data = write_buf.c_str();
    size_t remaining = write_buf.size();

    while (remaining > 0) {
        // 发送数据
        if ((bytes_sent = send(client_fd, data, remaining, 0)) <= 0) {
            // 出错处理
            if (bytes_sent == 0) {
                PRINTF_LOG_AND_DEBUG(LOG_WARNING, "Client closed connection");
            } else {
                PRINT_ERRNO_AND_STRERROR(errno, "Send error");
                return false;
            }
            clients_fd.erase(client_fd);
            close(client_fd);
            return true;
        }
        // 调整剩余数据长度
        remaining -= bytes_sent;
        data += bytes_sent;
    }
    return true;
}

bool MyServSocket::RecieveFromClient(const socketfd& client_fd, string &read_buf) {
    char buffer[4096];
    ssize_t bytes_read;

    while ((bytes_read = recv(client_fd, buffer, sizeof(buffer), 0)) > 0) {
        read_buf.append(buffer, bytes_read);
    }

    if (bytes_read == 0) {
        cout << "Client closed connection\n" << endl;
        clients_fd.erase(client_fd);
        close(client_fd);
    } else if (bytes_read < 0) {
        PRINT_ERRNO_AND_STRERROR(errno, "Msg receive completed\n");
    }
    return true;
}

// 析构函数实现
MyServSocket::~MyServSocket() {
    // 关闭所有客户端连接
    for (auto fd : clients_fd) {
        close(fd);
    }
    // 关闭服务器socket
    if (socket_fd >= 0) {
        close(socket_fd);
    }
}

socketfd MyServSocket::GetSocketfd() const {
    return socket_fd;
}